package org.jeecg.modules.gcProject.service.impl;

import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import org.apache.shiro.SecurityUtils;
import org.apache.xmlbeans.GDate;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.exOperationRecord.entity.ExOperationRecord;
import org.jeecg.modules.exOperationRecord.service.IExOperationRecordService;
import org.jeecg.modules.exProject.entity.ExProject;
import org.jeecg.modules.exProject.entity.ExSection;
import org.jeecg.modules.exProject.entity.ExTenderProject;
import org.jeecg.modules.exProject.service.impl.ExProjectServiceImpl;
import org.jeecg.modules.exProject.vo.ExProjectPage;
import org.jeecg.modules.gcProject.entity.GcProjectAttachment;
import org.jeecg.modules.gcProject.entity.GcProjectEntry;
import org.jeecg.modules.gcProject.entity.GcProjectEntrySection;
import org.jeecg.modules.gcProject.mapper.GcProjectAttachmentMapper;
import org.jeecg.modules.gcProject.mapper.GcProjectEntrySectionMapper;
import org.jeecg.modules.gcProject.mapper.GcProjectEntryMapper;
import org.jeecg.modules.gcProject.service.IGcProjectEntrySectionService;
import org.jeecg.modules.gcProject.service.IGcProjectEntryService;
import org.jeecg.modules.gcProject.vo.GcProjectAuditParam;
import org.jeecg.modules.gcProject.vo.StatusEnum;
import org.jeecgframework.poi.excel.annotation.Excel;
import org.jeecgframework.poi.excel.annotation.ExcelCollection;
import org.springframework.beans.BeanUtils;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Description: 项目进场
 * @Author: jeecg-boot
 * @Date: 2024-08-11
 * @Version: V1.0
 */
@Service
public class GcProjectEntryServiceImpl extends ServiceImpl<GcProjectEntryMapper, GcProjectEntry> implements IGcProjectEntryService {

    @Autowired
    private GcProjectEntryMapper gcProjectEntryMapper;
    @Autowired
    private GcProjectEntrySectionMapper gcProjectEntrySectionMapper;

    @Autowired
    private GcProjectAttachmentMapper gcProjectAttachmentMapper;
    @Autowired
    private ExProjectServiceImpl exProjectService;
    @Autowired
    private IGcProjectEntrySectionService gcProjectEntrySectionService;
    @Autowired
    private IExOperationRecordService exOperationRecordService;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveMain(GcProjectEntry gcProjectEntry, List<GcProjectEntrySection> gcProjectEntrySectionList, List<GcProjectAttachment> gcProjectAttachmentList) {
        gcProjectEntryMapper.insert(gcProjectEntry);
        if (gcProjectEntrySectionList != null && gcProjectEntrySectionList.size() > 0) {
            for (GcProjectEntrySection entity : gcProjectEntrySectionList) {
                entity.setId(null);
                //外键设置
                entity.setEntryId(gcProjectEntry.getId());
                gcProjectEntrySectionMapper.insert(entity);
            }
        }
        if (gcProjectAttachmentList != null && gcProjectAttachmentList.size() > 0) {
            for (GcProjectAttachment entity : gcProjectAttachmentList) {
                entity.setId(null);
                //外键设置
                entity.setEntryId(gcProjectEntry.getId());
                gcProjectAttachmentMapper.insert(entity);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMain(GcProjectEntry gcProjectEntry, List<GcProjectEntrySection> gcProjectEntrySectionList, List<GcProjectAttachment> gcProjectAttachmentList) {
        gcProjectEntryMapper.updateById(gcProjectEntry);

        //1.先删除子表数据
        gcProjectEntrySectionMapper.deleteByMainId(gcProjectEntry.getId());

        //2.子表数据重新插入
        if (gcProjectEntrySectionList != null && gcProjectEntrySectionList.size() > 0) {
            for (GcProjectEntrySection entity : gcProjectEntrySectionList) {
                //外键设置
                entity.setEntryId(gcProjectEntry.getId());
                gcProjectEntrySectionMapper.insert(entity);
            }
        }

        gcProjectAttachmentMapper.deleteByMainId(gcProjectEntry.getId());
        //2.子表数据重新插入
        if (gcProjectAttachmentList != null && gcProjectAttachmentList.size() > 0) {
            for (GcProjectAttachment entity : gcProjectAttachmentList) {
                //外键设置
                entity.setEntryId(gcProjectEntry.getId());
                gcProjectAttachmentMapper.insert(entity);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delMain(String id) {
        gcProjectEntrySectionMapper.deleteByMainId(id);
        gcProjectAttachmentMapper.deleteByMainId(id);
        gcProjectEntryMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delBatchMain(Collection<? extends Serializable> idList) {
        for (Serializable id : idList) {
            gcProjectAttachmentMapper.deleteByMainId(id.toString());
            gcProjectEntrySectionMapper.deleteByMainId(id.toString());
            gcProjectEntryMapper.deleteById(id);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean audit(GcProjectAuditParam gcProjectAuditParam) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        GcProjectEntry gcProjectEntry = this.getById(gcProjectAuditParam.getId());
        if (gcProjectEntry == null) {
            throw new JeecgBootException("未找到对应数据");
        }
        gcProjectEntry.setEntryStatus(gcProjectAuditParam.getEntryStatus());
        gcProjectEntry.setUpdateTime(new Date());
        gcProjectEntry.setUpdateBy(sysUser.getUsername());
        if(StatusEnum.SUCCESS.getCode().equals(gcProjectAuditParam.getEntryStatus())){
            ExProjectPage exProjectPage = new ExProjectPage();
            ExProject exProject = getExProjectInfo(gcProjectEntry);
            List<ExTenderProject> exTenderProjectList = Arrays.asList(getExTenderProject(gcProjectEntry));
            exProjectPage.setExTenderProjectList(exTenderProjectList);
            exProjectPage.setExSectionList(getExSectionList(gcProjectEntry));
            exProjectService.saveMain(exProject, exProjectPage.getExTenderProjectList(), exProjectPage.getExSectionList());
        }
        ExOperationRecord exOperationRecord = new ExOperationRecord();
        exOperationRecord.setEntryId(gcProjectEntry.getId());
        exOperationRecord.setModule("gcProjectEntry");
        exOperationRecord.setOperateTime(new Date());
        exOperationRecord.setOperateResult(StatusEnum.SUCCESS.getCode().equals(gcProjectAuditParam.getEntryStatus()) ? "1" : "2");//1 通过 2驳回
        exOperationRecord.setOperateOpinion(gcProjectAuditParam.getOperateOpinion());
        exOperationRecord.setCategory("1");
        exOperationRecord.setOperator(sysUser.getRealname());
        exOperationRecordService.save(exOperationRecord);
        return this.updateById(gcProjectEntry);
    }

    private ExProject getExProjectInfo(GcProjectEntry gcProjectEntry) {
        ExProject exProject = new ExProject();
        exProject.setProjectId(gcProjectEntry.getId());
        exProject.setProjectCode(gcProjectEntry.getProjectCode());
        exProject.setProjectName(gcProjectEntry.getProjectName());
        exProject.setRegionCode(gcProjectEntry.getXmszqy());
        exProject.setInvestProjectCode(gcProjectEntry.getTzxmtydm());
        exProject.setAddress(gcProjectEntry.getXmdz());
        exProject.setLegalPerson("");//项目法人
        exProject.setIndustriesType(gcProjectEntry.getXmhyfl());
        exProject.setFundSource(gcProjectEntry.getZjly());
        exProject.setContributionScale(gcProjectEntry.getCzbl());
        exProject.setProjectScale(gcProjectEntry.getXmgm());
        exProject.setContactor(gcProjectEntry.getZblxr());
        exProject.setContactInformation(gcProjectEntry.getZblxfs());
        exProject.setIslixiang("");
        exProject.setNotlixiang("");
        exProject.setSuperviseDeptName(gcProjectEntry.getJddw());//监督单位
        exProject.setSuperviseDeptCode("");
        exProject.setApprovalName("");//项目审批文件名称
        exProject.setApprovalNumber("");//项目审批文号
        exProject.setApprovalAuthority("");//项目审批单位
        exProject.setAttachmentCode("");//附件关联标识号
        exProject.setSysPlatformCode(gcProjectEntry.getSysPlatformCode());//交易系统标识码
        exProject.setStateOwnedFund(BigDecimal.ZERO);//国有资金（万元）
        exProject.setStateOwnedFundRatio(BigDecimal.ZERO);//国有资金比例
        exProject.setPrivateFund(BigDecimal.ZERO);//私有资金（万元）
        exProject.setPrivateFundRatio(BigDecimal.ZERO);//私有资金比例
        exProject.setForeignFund(BigDecimal.ZERO);//外国政府及组织投资（万元）
        exProject.setForeignFundRatio(BigDecimal.ZERO);//外国政府及组织投资比例
        exProject.setForeignPrivateFund(BigDecimal.ZERO);//境外私人投资（万元）
        exProject.setForeignPrivateFundRatio(BigDecimal.ZERO);//境外私人投资比例


        exProject.setAgencyCode(gcProjectEntry.getDljgxydm());
        exProject.setAgencyName(gcProjectEntry.getDljg());
        exProject.setTenderCode(gcProjectEntry.getZbshxydm());
        exProject.setTenderName(gcProjectEntry.getZbbz());

        exProject.setCreateTime(new Date());
        exProject.setStatus(StatusEnum.SAVE.getCode());
        return exProject;
    }

    private ExTenderProject getExTenderProject(GcProjectEntry gcProjectEntry) {
        ExTenderProject exTenderProject = new ExTenderProject();
        exTenderProject.setTenderProjectId("");
        exTenderProject.setProjectId(gcProjectEntry.getId());//项目标识码 (guid)
        exTenderProject.setProjectCode(gcProjectEntry.getProjectCode());//项目编号
        exTenderProject.setTenderProjectCode(gcProjectEntry.getProjectCode());//招标项目编号
        exTenderProject.setUnifiedDealCode("");//统一交易标识码
        exTenderProject.setTenderProjectName(gcProjectEntry.getProjectName());//招标项目名称
        exTenderProject.setTenderProjectIndustriesType(gcProjectEntry.getXmhyfl());//招标项目行业分类
        exTenderProject.setTenderProjectType(gcProjectEntry.getXmlxdm());//招标项目类型
        exTenderProject.setEntityType(gcProjectEntry.getTzzt());//招标主体性质
        exTenderProject.setRegionCode(gcProjectEntry.getXmszqy());//招标项目所在行政区域代码
        exTenderProject.setTenderContent("");//招标内容与范围及招标方案说明
        exTenderProject.setOwnerName("");//项目业主名称
        exTenderProject.setTendererName(gcProjectEntry.getZbbz());//招标人名称
        exTenderProject.setTendererCodeType("");//招标人类别
        exTenderProject.setTendererCode(gcProjectEntry.getZbxmbab());//招标人代码
        exTenderProject.setTendererRole("");//招标人角色
        exTenderProject.setTenderAgencyName(gcProjectEntry.getDljg());//招标代理机构名称
        exTenderProject.setTenderAgencyCodeType("");//招标代理机构类别
        exTenderProject.setTenderAgencyCode(gcProjectEntry.getDljgxydm());//招标代理机构代码
        exTenderProject.setTenderAgencyRole("");//招标代理机构角色
        exTenderProject.setTenderMode(gcProjectEntry.getZbfs());//招标方式
        exTenderProject.setTenderOrganizeForm("");//招标组织形式
        exTenderProject.setSuperviseDeptName("");//监督部门名称
        exTenderProject.setSuperviseDeptCode("");//监督部门代码
        exTenderProject.setApproveDeptName("");//审核部门名称
        exTenderProject.setApproveDeptCode("");//审核部门代码
        exTenderProject.setAttachmentCode("");//附件关联标识号
        exTenderProject.setPlatformCode("");//交易系统标识
        return exTenderProject;
    }

    private List<ExSection> getExSectionList(GcProjectEntry gcProjectEntry) {
        List<ExSection> exSectionList = new ArrayList<>();
        List<GcProjectEntrySection> gcProjectEntrySectionList = gcProjectEntrySectionMapper.selectByMainId(gcProjectEntry.getId());
        for (GcProjectEntrySection item : gcProjectEntrySectionList) {
            ExSection exSection = new ExSection();
            exSection.setProjectId(item.getEntryId());
            exSection.setTenderProjectCode(gcProjectEntry.getProjectCode());
            exSection.setBidSectionCode(item.getSectionCode());//标段（包）编
            exSection.setTenderProjectId("");//招标项目标识码 (guid
            exSection.setOldbidSectionId("");//原标段（包）标识码 (guid
            exSection.setIszhongzhi("");//标段（包）状态 (暂停-1、终止-2
            exSection.setZhongzhiInfo("");//暂停/终止原
            exSection.setBidSectionName(item.getSectionName());//标段（包）名
            exSection.setSuperviseDeptName("");//监督部门名
            exSection.setSuperviseDeptCode("");//监督部门代
            exSection.setUnifiedDealCode("");//统一交易标识
            exSection.setBidSectionContent("");//标段（包）内
            exSection.setTenderProjectClassifyCode("");//标段（包）分类代
            exSection.setContractReckonPrice(null);//标段合同估算
            exSection.setCurrencyCode("");//标段合同估算价币种代
            exSection.setPriceUnit("");//标段合同估算价单
            exSection.setBidQualification("");//投标人资格条
            exSection.setBeginDate(item.getJhkgrq());//计划开工日
            exSection.setLimiteTime(null);//工期 (单位：天)
            exSection.setCreateTime(new Date());
            exSection.setPlatformCode("");
            exSection.setBidDate(new Date());
            exSection.setIsWebBidding("");
            exSectionList.add(exSection);
        }
        return exSectionList;
    }
}
